package com.ewei.web.authority.shiro.page;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.util.StringUtils;

/**
 * 实现对页面细粒度的权限控制(对象层次)
 * @author David
 */
public class PageAccessFilter extends AccessControlFilter{
	private final String DEFAULT_SUFFIX = "/page";
	private String suffix  = DEFAULT_SUFFIX;
	private String unauthorizedUrl = null;
	public String getUnauthorizedUrl() {
		return unauthorizedUrl;
	}
	public void setUnauthorizedUrl(String unauthorizedUrl) {
		this.unauthorizedUrl = unauthorizedUrl;
	}
	
	public String getSuffix() {
		return suffix;
	}
	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}
	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		return false;
	}
	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		if(!subject.isAuthenticated()){
			String username = (String) subject.getPrincipal();//is username
			String url = httpRequest.getRequestURI();
			String patternStr = "(?<="+suffix+"/)[\\s\\S]*";
			Pattern pattern =Pattern.compile(patternStr);
			Matcher matcher = pattern.matcher(url);
			matcher.find();
			String resourceURL = matcher.group();
			if(StringUtils.isEmpty(resourceURL)){
				//TODO get the Resources by username
				boolean checkResult = true; 
				if(checkResult){ return true;}
			}
		}
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		httpResponse.sendRedirect(httpRequest.getContextPath()+unauthorizedUrl);
		return false;
	}
}
